package com.hushan.elevator.utils;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;
public class deviceConnect {
    public static void main(String[] args) throws Exception {
        int port = 8080;
        // 创建一个HTTP服务器，监听指定端口
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
        // 注册处理器，处理 /event 路径的POST请求
        server.createContext("/event", new EventHandler());
        // 注册处理器，处理 /picture 路径的POST请求
        server.createContext("/picture", new PictureHandler());
        server.setExecutor(null); // 默认的Executor
        System.out.println("Starting server on port " + port + "...");
        server.start(); // 启动服务器
    }


    // 处理 /event 请求的处理器
    static class EventHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) { // 仅处理POST请求
                // 读取请求体
                InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "utf-8");
                BufferedReader br = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                String requestBody = sb.toString();
                System.out.println("Received event data: " + requestBody);

                // 处理事件数据
                // 在这里添加处理事件数据的代码

                // 发送响应
                String response = "Event received";
                exchange.sendResponseHeaders(200, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            } else {
                exchange.sendResponseHeaders(405, -1); // 方法不允许
            }
        }
    }

    // 处理 /picture 请求的处理器
    static class PictureHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) { // 仅处理POST请求
                // 获取boundary
                String boundary = getBoundary(exchange.getRequestHeaders().getFirst("Content-Type"));
                // 解析multipart请求
                Map<String, byte[]> parts = parseMultipart(exchange.getRequestBody(), boundary);

                for (Map.Entry<String, byte[]> entry : parts.entrySet()) {
                    String filename = entry.getKey();
                    byte[] content = entry.getValue();

                    // 保存图片到images文件夹
                    File file = new File("images/" + filename);
                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        fos.write(content);
                    }
                    System.out.println("Received picture: " + filename);
                }

                // 发送响应
                String response = "Picture received";
                exchange.sendResponseHeaders(200, response.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(response.getBytes());
                os.close();
            } else {
                exchange.sendResponseHeaders(405, -1); // 方法不允许
            }
        }

        // 从Content-Type头部获取boundary
        private String getBoundary(String contentType) {
            String boundary = null;
            for (String param : contentType.split(";")) {
                if (param.trim().startsWith("boundary=")) {
                    boundary = param.split("=")[1];
                }
            }
            return boundary;
        }

        // 解析multipart请求
        private Map<String, byte[]> parseMultipart(InputStream inputStream, String boundary) throws IOException {
            Map<String, byte[]> parts = new HashMap<>();
            byte[] boundaryBytes = ("--" + boundary).getBytes("UTF-8");
            byte[] endBoundaryBytes = ("--" + boundary + "--").getBytes("UTF-8");

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int bytesRead;
            byte[] data = new byte[1024];
            while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }

            byte[] inputBytes = buffer.toByteArray();
            int startPos = 0;
            while (startPos < inputBytes.length) {
                int boundaryPos = indexOf(inputBytes, boundaryBytes, startPos);
                int endBoundaryPos = indexOf(inputBytes, endBoundaryBytes, startPos);

                if (boundaryPos == -1 && endBoundaryPos == -1) break;

                int partStart = boundaryPos + boundaryBytes.length + 2;
                int partEnd = indexOf(inputBytes, boundaryBytes, partStart);

                if (partEnd == -1) partEnd = endBoundaryPos;

                byte[] partBytes = new byte[partEnd - partStart - 4];
                System.arraycopy(inputBytes, partStart + 4, partBytes, 0, partBytes.length);

                int headerEndPos = indexOf(partBytes, "\r\n\r\n".getBytes("UTF-8"), 0);
                if (headerEndPos != -1) {
                    String headers = new String(partBytes, 0, headerEndPos, "UTF-8");
                    String filename = headers.split("filename=\"")[1].split("\"")[0];
                    byte[] content = new byte[partBytes.length - headerEndPos - 4];
                    System.arraycopy(partBytes, headerEndPos + 4, content, 0, content.length);
                    parts.put(filename, content);
                }

                startPos = partEnd + boundaryBytes.length;
            }

            return parts;
        }

        // 查找目标字节数组在源字节数组中的索引
        private int indexOf(byte[] array, byte[] target, int start) {
            outer:
            for (int i = start; i < array.length - target.length + 1; i++) {
                for (int j = 0; j < target.length; j++) {
                    if (array[i + j] != target[j]) {
                        continue outer;
                    }
                }
                return i;
            }
            return -1;
        }
    }
}
